<template>
  <div>
    <!--
      必备
        action 上传地址必填, 现在没有放个 # 即可
      样式
        list-type 控制显示的样式, 给个 picture-card
     -->;
    <el-upload :on-change="onchange" :on-preview="onpreview" :before-upload="beforeupload" :http-request="httprequest" :on-remove="onremove" list-type="picture-card" action="#" :file-list="fileList" :class="{disable:fileList.length>0}">
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowProgress" :text-inside="true" :stroke-width="26" :percentage="percentage" style="width:146px" />
    <el-dialog :visible="isShowDialog" title="预览照片" @close="isShowDialog=false">
      <el-row type="flex" justify="center">
        <img :src="dialogImg" alt="">
      </el-row>

    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDykGVTAajcEagYAWbOvBBtPedLmwqTgdJ',
  SecretKey: 'RaU7UaPxFH1UgaDagW5MM6ZlfIeiV1GE'
})
// 这个实例带上了我们的SecretId 和 SecretKey 可以验证我们的身份
export default {
  data() {
    return {
      percentage: 0,
      fileList: [],
      isShowDialog: false,
      dialogImg: '',
      isShowProgress: false
    }
  },
  created() {
    // console.log(39, cos)
  },
  methods: {
    onpreview(file) {
      this.isShowDialog = true
      console.log(file)
      this.dialogImg = file.url
    },
    onremove(file, fileList) {
      this.fileList = fileList
    },
    onchange(file, fileList) {
      this.fileList = fileList
    },
    // 上传文件之前的钩子
    beforeupload(file) {
      console.log('上传前的校验', file)
      const MaxSize = 2 * 1024 * 1024
      if (file.size > MaxSize) {
        this.$message.warning('只能上传2M的图片')
        return false
      }
      //   定义一个白名单
      const whiteList = ['image/jpeg', 'image/png']
      //   校验是否符合图片格式
      if (!whiteList.includes(file.type)) {
        this.$message.warning('只支持jpeg跟png格式的图片')
        return false
      }
    },
    httprequest(params) {
    //   console.log('上传逻辑', params)
      cos.putObject({
        Bucket: 'hr-77-1309020580', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          this.isShowProgress = true
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].status = 'success'
          this.fileList[0].url = 'http://' + data.Location
        }
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
      })
    }

  }
}
</script>

<style lang="scss"  scoped>
.disable{
::v-deep  .el-upload--picture-card{
        display: none;
    }
}
::v-deep img{
    object-fit: contain;
}

</style>

